package com.example.onlineanswer.controller;

import com.example.onlineanswer.common.annotation.RequiresLogin;
import com.example.onlineanswer.common.api.CommonResult;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api/file")
@RequiredArgsConstructor
public class FileController {

    @Value("${file.upload.path:./src/main/resources/static/uploads/}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:/uploads/}")
    private String urlPrefix;

    /**
     * 上传图片文件
     *
     * @param file 图片文件
     * @return 图片URL
     */
    @PostMapping("/upload/image")
    @RequiresLogin
    public CommonResult<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed("请选择文件");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return CommonResult.failed("只能上传图片类型文件");
        }

        try {
            // 创建基础目录结构
            String dateFolder = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            Path uploadDir = Paths.get(uploadPath + dateFolder);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = StringUtils.getFilenameExtension(originalFilename);
            String newFilename = UUID.randomUUID().toString() + "." + extension;

            // 保存文件
            String filePath = dateFolder + "/" + newFilename;
            Path destPath = Paths.get(uploadPath + filePath);
            Files.copy(file.getInputStream(), destPath);

            // 返回文件URL
            String fileUrl = urlPrefix + filePath;
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("filename", newFilename);

            return CommonResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传竞赛封面图片
     *
     * @param file 封面图片
     * @return 封面URL
     */
    @PostMapping("/upload/contest-cover")
    @RequiresLogin
    public CommonResult<Map<String, String>> uploadContestCover(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return CommonResult.failed("请选择文件");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || (!contentType.equals("image/jpeg") && !contentType.equals("image/png"))) {
            return CommonResult.failed("封面图片只能上传jpg或png格式");
        }

        // 检查文件大小（限制为2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            return CommonResult.failed("封面图片大小不能超过2MB");
        }

        try {
            // 创建竞赛封面专用目录
            String contestFolder = "contests/covers";
            Path uploadDir = Paths.get(uploadPath + contestFolder);
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = StringUtils.getFilenameExtension(originalFilename);
            String newFilename = UUID.randomUUID().toString() + "." + extension;

            // 保存文件
            String filePath = contestFolder + "/" + newFilename;
            Path destPath = Paths.get(uploadPath + filePath);
            Files.copy(file.getInputStream(), destPath);

            // 返回文件URL
            String fileUrl = urlPrefix + filePath;
            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("filename", newFilename);

            return CommonResult.success(result);
        } catch (IOException e) {
            e.printStackTrace();
            return CommonResult.failed("封面上传失败：" + e.getMessage());
        }
    }
}

/**
 * 静态资源访问配置
 */
@Configuration
class FileResourceConfig implements WebMvcConfigurer {

    @Value("${file.upload.path:./src/main/resources/static/uploads/}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:/uploads/}")
    private String urlPrefix;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置外部静态资源映射
        registry.addResourceHandler(urlPrefix + "/**")
                .addResourceLocations("file:" + uploadPath);
    }
} 